<template>
  <div class="contain">
    <!-- <div class="hd mt10">
      <img src="../../assets/yzf_Bg.png" alt="">
    </div> -->
    <search-bar :menu="menu" :showsearch="false" :activeitem="activeitem"></search-bar>
    <free :freeDialog="freeDialog" :nextUrl="nextUrl" :type="type"></free>
    <div class="content">
      <div class="border_content bg-white">
        <div class="price">
          <span>支付费用：</span>
          <span>{{budgetres && budgetres.selfPay}}</span>
          <span>元</span>
        </div>
        <div class="border"></div>

        <div v-if="!showSVG">
          <div class="pay_type_title">
            <p>请选择支付方式</p>
          </div>
          <div class="pay_type">
            <div class="zhifubao">
              <el-radio v-model="radio" label="02"> <img src="../../assets/支付宝.png" alt=""></el-radio>&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
              <span>推荐支付宝账户使用</span>
            </div>
            <div class="wechat">
              <el-radio v-model="radio" label="03"> <img src="../../assets/微信支付.png" alt=""> </el-radio>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span>微信快捷支付</span>
            </div>
          </div>
          <div class="border"></div>

          <div class="button">
            <router-link to="/cloud_mail">返回</router-link>
            <a href="javascript:;" class="common-main-button" @click="submitPay">下一步</a>
          </div>
        </div>
        <div v-else class="hd" style="width:512px;margin:40px auto;">
          <div class="qrcode-wrapper" v-if="this.radio === '02'">
            <div v-html="qrcodeSrc" class="qrcode alipay"></div>
          </div>

          <div class="qrcode-wrapper wxpay" v-if="this.radio === '03'">
            <div v-html="qrcodeSrc" class="qrcode wxpay"></div>
          </div>

          <div class="qrcode-text ">二维码有效时间
            <span class="t1">{{qrcodeSeconds}}</span> 秒
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import QRCode from 'qr-image'
  import Steps from '../../components/Steps'
  import SearchBar from '../../components/SearchBar'
  import position from '../../components/Position'
  import free from '../../components/free.vue'
  import { commonAjax, ORG_ID, PLATFORM_PREFIX, CLOUD_MENU } from '../../api/api'
  export default {
    data () {
      return {
        menu: CLOUD_MENU,
        activeitem: 2,
        m: 0,
        s: 0,
        outTime: false,
        dep: JSON.parse(localStorage.dep || '{}'),
        order: JSON.parse(localStorage.order || '{}'),
        time: JSON.parse(localStorage.time || '{}'),
        list: {},
        radio: '02',
        qrcodeSrc: '',
        showSVG: false,
        timer: null,
        qrcodeSeconds: 60,
        payTypeName: '支付宝',
        obj: this.$route.query,
        budgetres: {},
        paylist: [],
        freeDialog: false,
        nextUrl: '/cloud_mail/pay_result',
        type: 'drugFee'
      }
    },
    mounted () {
      this.preBudget()
    },
    beforeDestroy () {
      let self = this
      if (this.timer) {
        clearInterval(self.timer)
        this.timer = null
      }
    },
    methods: {
      preBudget () {
        // 预结算费用
        let temparr = []
        for (let i = 0; i < this.obj.feeRecords.length; i++) {
          temparr.push({
            feeTypeCode: this.obj.feeRecords[i].feeTypeCode,
            feeNo: this.obj.feeRecords[i].feeNo,
            fried: 0
          })
        }
        this.paylist = temparr
        commonAjax([ORG_ID, this.obj.patientId, temparr, 'HCN-WEB'], `${PLATFORM_PREFIX}.diagnosisPayTradeService`, 'getPrecalculatedFee').then(res => {
          if (res.data.code === 200) {
            this.budgetres = res.data.body.response
            if (parseFloat(this.budgetres.selfPay) === 0) {
              this.freeDialog = true
            }
            localStorage.drugBudgetRes = JSON.stringify(this.budgetres)
          }
        })
      },
      submitPay () {
        let config = {
          orgId: ORG_ID,
          totalAmount: this.budgetres.selfPay,
          accountType: this.radio,
          outTradeNo: this.budgetres.payServerTradeNo,
          payModel: 2,
          body: JSON.stringify({
            bustype: '71',
            id: this.budgetres.precalId,
            patientId: this.obj.patientId,
            precalId: this.budgetres.precalId,
            payer: JSON.parse(localStorage.person).personName,
            source: 'HCN-WEB',
            feeRecords: this.paylist
          })
        }
        this.$store.commit('UPDATE_LOADING')
        commonAjax(
          [config],
          `${PLATFORM_PREFIX}.payService`,
          'getOrderStr'
        ).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 200) {
            let _this = this
            this.qrcodeSrc = QRCode.imageSync(res.data.body, { type: 'svg' })
            this.showSVG = true
            if (this.radio === '03') {
              this.payTypeName = '微信'
            }
            let qrtimer = setInterval(() => {
              if (_this.qrcodeSeconds <= 0) {
                clearInterval(qrtimer)
              } else {
                _this.qrcodeSeconds--
              }
            }, 1000)
            if (this.timer) {
              clearInterval(this.timer)
            }
            this.queryAliOrder()
          } else {
            this.$message({
              message: '请求服务端失败',
              type: 'error'
            })
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
          this.$message({
            message: '请求服务端失败',
            type: 'error'
          })
        })
      },
      queryAliOrder () {
        let i = 0
        const TIME_OUT = 60
        // 支付二维码超时时间（秒）
        const PER_TIME = 3
        // 轮询间隔（秒）
        let _this = this
        this.timer = setInterval(() => {
          i++
          commonAjax([{
            orgId: ORG_ID,
            outTradeNo: this.budgetres.payServerTradeNo,
            accountType: this.radio
          }], `${PLATFORM_PREFIX}.payService`, 'queryAliOrder').then(res => {
            if (res.data.body) {
              clearInterval(_this.timer)
              this.$router.push('/cloud_mail/pay_result?result=victory')
            } else if (i < (TIME_OUT / PER_TIME)) {
              console.log('checking order status...' + i)
            } else {
              clearInterval(_this.timer)
              this.$router.push('/cloud_mail/pay_result?result=defeat')
            }
          })
        }, PER_TIME * 1000)
      }
    },
    components: {Steps, position, SearchBar, free}
  }
</script>

<style lang="less">
  .contain {
    margin-bottom: 100px;
    .content {
      width: 1080px;
      margin: 0 auto;
      background-color: #ffffff;
      overflow: hidden;
    }
    .content .flow {
      margin-top: 20px;
    }
    .border_content .price {
      margin-left: 48px;
      margin-top: 50px;
    }
    .border_content .border {
      width: 1010px;
      margin: 0 auto;
      height: 1px;
      background-color: rgb(245, 230, 227);
      margin-top: 30px;
    }
    .border_content .price span:nth-of-type(1) {
      font-size: 18px;
      display: inline-block;
    }
    .border_content .price span:nth-of-type(2) {
      font-size: 18px;
      display: inline-block;
      color: #993333;
    }
    .border_content .price span:nth-of-type(3) {
      font-size: 18px;
    }
    .border_content .pay_left_time {
      margin-left: 48px;
      margin-top: 24px;
    }
    .border_content .pay_left_time span:nth-of-type(1) {
      font-size: 16px;
      color: #ff9900;
    }
    .border_content .pay_left_time span:nth-of-type(2) {
      font-size: 16px;
      color: #993333;
    }
    .border_content .pay_left_time span:nth-of-type(3) {
      font-size: 16px;
      color: #ff9900;
    }
    .border_content .pay_type_title {
      margin-top: 44px;
      margin-left: 48px;
      color: #666666;
      font-size: 14px;
    }
    .border_content .pay_type {
      width: 1016px;
      height: 156px;
      background-color: rgb(254, 251, 248);
      margin: 0 auto;
      overflow: hidden;
    }
    .border_content .pay_type img {
      vertical-align: middle;
    }
    .border_content .pay_type .zhifubao {
      margin-top: 30px;
      margin-left: 20px;
    }
    .border_content .pay_type .wechat {
      margin-top: 30px;
      margin-left: 20px;
    }
    .border_content .button {
      margin-left: 58px;
      margin-top: 30px;
      padding-bottom: 60px;
    }
    .border_content .button a:nth-of-type(1) {
      display: inline-block;
      width: 128px;
      height: 40px;
      background: url(../../assets/前往付费.png) 0 0 no-repeat;
      background-size: 100% 100%;
      text-align: center;
      line-height: 40px;
      color: #ffcc99;
    }
    .border_content .button a:nth-of-type(2) {
      display: inline-block;
      width: 128px;
      height: 40px;
      background: url(../../assets/返回.png) 0 0 no-repeat;
      background-size: 100% 100%;
      text-align: center;
      line-height: 40px;
      color: #663300;
      margin-left: 10px;
    }
    .qrcode-wrapper {
      width: 512px;
      height: 678px;
      background: url(../../assets/payType.jpg) no-repeat;
      position: relative;
      &.wxpay {
        background-position: -512px 0;
      }
    }
    .qrcode {
      width: 170px;
      height: 170px;
      border-radius: 10px;
      position: absolute;
      top: 250px;
      left: 170px;
    }
    .qrcode-text {
      margin: 20px;
      text-align: center;
    }
  }
</style>
